<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name:  Setup Model
*
* Author:  William Bermudo
*
*/

class Transaction_m extends CI_Model {
	
	public function __construct()
	{
		parent::__construct();
		$this->config->load('transaction/transact', TRUE);
		$this->tables  = $this->config->item('tables');
		$table = $this->tables['invoices'];
	}
    
    public function create_invoice_transaction()
    {
        $user_id 	 = $this->session->userdata('id');
        $customer_id = $this->input->post('customer_id');
        $invoice_num = $this->input->post('number');
        
        $data = array('invoice_number' => $invoice_num,
                      'user_id' => $user_id,
                      'customer_id' => $customer_id,
                      'date_created' => now());
        
        $this->db->insert('birth_invoices', $data);
        $id = $this->db->insert_id();
        
        if ($id)
        { 
            $this->insert_invoice_transaction_line($id);
        }
    }
    
    public function insert_invoice_transaction_line($id)
    {
        $items      = $this->input->post('item_id');
        $quantity   = $this->input->post('quantity');
        $rate       = $this->input->post('rate');
        $term       = $this->input->post('term');
        $amount     = $this->input->post('amount');
        
        foreach($items as $key => $value)
        {
            $data = array('invoice_id'  => $id,
                          'item_id'     => $value,
                          'item_qty'    => $quantity[$key],
                          'item_rate'   => $rate[$key],
                          'item_amount' => $amount[$key]);
            
            $this->db->insert('birth_invoice_transaction_lines', $data);
        }
    }
	
	public function get_all_invoice_header($id)
	{
		$this->db->select('id, invoice_number, date_created');
		$this->db->where('customer_id', $id);
		$this->db->from('birth_invoices');
		$query = $this->db->get();
		
		if ($query->num_rows() > 0)
		{
			return $query->result();
		}
		
		return null;
	}
}